package com.zmj.mobile.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmj.framework.response.Result;
import com.zmj.mobile.dto.MobileListVO;
import com.zmj.mobile.dto.MobilePageRequest;
import com.zmj.mobile.entity.OrgEntity;
import com.zmj.mobile.enums.FlowTypeEnum;
import com.zmj.mobile.service.IOrgService;
import com.zmj.modules.flow.entity.dto.BpmTaskCcQueryDto;
import com.zmj.modules.flow.entity.dto.BpmTaskFinishQuery;
import com.zmj.modules.flow.service.FlowableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @DATE 2024/2/1 22:37
 * @AUTHOR zhaizongwei
 */
@RestController
@Api(tags = {"PageController"})
@RequestMapping("/v1/api")
public class PageController {

    @Resource
    private FlowableService flowableService;
    @Resource
    private IOrgService iOrgService;

    @ApiOperation(value = "分页列表")
    @PostMapping("/page")
    public Result<?> page(@RequestBody MobilePageRequest request) {
        Page<MobileListVO> page = new Page<>();

        Integer type = request.getType();
        Integer menu = request.getMenu();
        if (menu == 0) {
            BpmTaskCcQueryDto query = new BpmTaskCcQueryDto();
            query.setCurrent(request.getPageNum());
            query.setSize(request.getPageSize());
            query.setCategory("");
            query.setAssignee(request.getCurrentUser());
            query.setProcInstName(FlowTypeEnum.getExample(type).getLabel());

            Result<Map<String, Object>> result = flowableService.getAllTodoTasks(query);
            return getPageResult(result, page);
        }
        if (menu == 1) {
            BpmTaskFinishQuery query = new BpmTaskFinishQuery();
            query.setCurrent(request.getPageNum());
            query.setSize(request.getPageSize());
            query.setCategory("");
            query.setCurrentUserId(request.getCurrentUser());
            query.setProcInstName(FlowTypeEnum.getExample(type).getLabel());

            Result<Map<String, Object>> result = flowableService.getFinishTasks(query);
            return getPageResult(result, page);
        }
        if (menu == 2) {
            BpmTaskFinishQuery query = new BpmTaskFinishQuery();
            query.setCurrent(request.getPageNum());
            query.setSize(request.getPageSize());
            query.setCategory("");
            query.setStartUser(request.getCurrentUser());
            query.setProcInstName(FlowTypeEnum.getExample(type).getLabel());

            Result<Map<String, Object>> result = flowableService.getAllProcessInstance(query);
            return getPageResult(result, page);
        }
        return Result.success(page);
    }

    private Result<Page<MobileListVO>> getPageResult(Result<Map<String, Object>> result, Page<MobileListVO> page) {
        Map<String, Object> dataMap = result == null ? null : result.getData();
        if (dataMap == null) {
            return Result.success(page);
        }
        Page<Map<String, Object>> data = BeanUtil.fillBeanWithMap(dataMap, new Page<>(), false);
        List<Map<String, Object>> records = data.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return Result.success(page);
        }
        List<MobileListVO> collect = records.stream().filter(Objects::nonNull).map(item -> MobileListVO.builder().id(String.valueOf(item.get("businessKey"))).auditName(String.valueOf(item.get("procInstName"))).creatorName(String.valueOf(item.get("startUserName"))).userNo(String.valueOf(item.get("startUser"))).createTime(String.valueOf(item.get("procInstStartTime"))).procInstStatus(String.valueOf(item.get("procInstStatus"))).build()).collect(Collectors.toList());
        collect.stream().filter(item -> StringUtils.isNotBlank(item.getUserNo())).forEach(item -> {
            Optional<OrgEntity> orgEntityOptional = iOrgService.getByUserName(item.getUserNo());
            orgEntityOptional.ifPresent(orgEntity -> item.setDept(orgEntity.getOrgName()));
        });

        Page<MobileListVO> resultPage = new Page<>();
        resultPage.setPages(data.getPages());
        resultPage.setTotal(data.getTotal());
        resultPage.setRecords(collect);
        return Result.success(resultPage);
    }
}
